package com.engine.ld.optimize;

import com.weaver.general.BaseBean;
import com.weaver.general.Util;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import weaver.conn.RecordSet;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/7/13
 */
public class Wlzsj {
    private static final BaseBean bb = new BaseBean();

    public String doWlzsj(String requestid) throws ParserConfigurationException {
        String where = " WHERE REQUESTID = " +requestid;
        String[] groupParams = {"MATNR","MTART","ZSPRAS","ZMAKTX","ESPRAS",
                "EMAKTX","MEINS","MATKL","BISMT","SPART","MSTAE","MSTDE",
                "MTPOS_MARA","BRGEW","NTGEW","GEWEI","GROES","CLASS","XCHPF",
                "MSTAV","MSTDV","ALAND","TATYP","TAXKM","TRAGR","RAUBE",
                "IPRKZ","ZFLAGJTC","SICHT_K","SICHT_V","SICHT_E","SICHT_D",
                "SICHT_P","SICHT_A","SICHT_F","SICHT_L","SICHT_S","SICHT_Q",
                "SICHT_B","SICHT_G","ZCLASS_S","LOEVMJTC"};
//        groupParams数组中BISMT   SICHT_P  SICHT_Q  字段不参加select操作
        String groupSql = "select ZFLAGJTC,LOEVMJTC,MATNR,MTART,ZSPRAS,ZMAKTX,ESPRAS,EMAKTX,MEINS,MATKL,SPART,MSTAE,MSTDE,MTPOS_MARA,BRGEW,NTGEW,GEWEI,GROES,CLASS,XCHPF,MSTAV,MSTDV,ALAND,TATYP,TAXKM,TRAGR,RAUBE,IPRKZ,ZFLAG,SICHT_K,SICHT_V,SICHT_E,SICHT_D,SICHT_A,SICHT_F,SICHT_L,SICHT_S,SICHT_B,SICHT_G,ZCLASS_S,LOEVM from formtable_main_117 a left join formtable_main_117_dt1 b on a.id=b.mainid";
//        获取group节点所需要的数据
//        bb.writeLog("group节点的查询sql是："+groupSql+where);
        Map<String, Object> groupMap = Data(groupParams, groupSql + where);
//        存储factory节点所需要的数据factoryMap


        String[] factoryParams = {"MATNR","WERKS","LGORT","EKGRP","MTVFP","LADGR","PRCTR",
                "MMSTA","DISMM","DISPO","DISLS","BSTMI","BSTRF","BESKZ",
                "SOBSL","LGPRO","RGEKZ","LGFSB","DZEIT","PLIFZ","WEBAZ",
                "MRPPP","FHORI","EISBE","EISLO","PERKZ","STRGR","VRMOD",
                "VINT1","VINT2","SBDKZ","FEVOR","SFCPF","UEETO","BKLAS",
                "VPRSV","PEINH","VERPR","STPRS","EKALR","HKMAT","AWSLS",
                "LOSGR","MEINS","ZFLAGGCC","LOEVMGCC"};

        String[] shortfactoryParams1 = {"ZFLAGGCC","LOEVMGCC","WERKS","LGORT","EKGRP","MTVFP","LADGR","PRCTR","MMSTA","DISMM","DISPO","DISLS","BSTMI","BSTRF","SOBSL","LGPRO","RGEKZ","LGFSB","DZEIT","PLIFZ","WEBAZ","MRPPP","FHORI","EISBE","EISLO","STRGR","VRMOD","VINT1","VINT2","SBDKZ","FEVOR","SFCPF","UEETO","BKLAS","VPRSV","PEINH","VERPR","STPRS","EKALR","HKMAT","AWSLS","LOSGR","MEINS"};
        String[] shortfactoryParams2 = {"BESKZ","MATNR"};
//        所有sql书写时必须添加where条件

        String factorySql1 = "select ZFLAGGCC,LOEVMGCC,WERKS,LGORT,EKGRP,MTVFP,LADGR,PRCTR,MMSTA,DISMM,DISPO,DISLS,BSTMI,BSTRF,SOBSL,LGPRO,RGEKZ,LGFSB,DZEIT,PLIFZ,WEBAZ,MRPPP,FHORI,EISBE,EISLO,STRGR,VRMOD,VINT1,VINT2,SBDKZ,FEVOR,SFCPF,UEETO,BKLAS,VPRSV,PEINH,VERPR,c.STPRS,EKALR,HKMAT,AWSLS,LOSGR,d.MEINS from ((((formtable_main_117 f left join formtable_main_117_dt1 a on f.id=a.mainid) left join formtable_main_117_dt2 b on f.id = b.mainid) left join formtable_main_117_dt3 c on f.id = c.mainid) left join formtable_main_117_dt4 d on f.id = d.mainid) left join formtable_main_117_dt5 e on f.id = e.mainid";
        String factorySql2 = "select BESKZ,MATNR from formtable_main_117 a join formtable_main_117_dt3 c on a.id=c.mainid";
//        bb.writeLog("factory节点的查询sql1是："+factorySql1+where);
//        bb.writeLog("factory节点的查询sql2是："+factorySql2+where);


        Map<String, Object> factoryMap1 = Data(shortfactoryParams1,factorySql1+where);
//        bb.writeLog("sureNullPoint01------");
//        bb.writeLog("factoryMap1集合："+factoryMap1);
        Map<String, Object> factoryMap2 = Data(shortfactoryParams2, factorySql2+where);
//        bb.writeLog("sureNullPoint02------");
//        bb.writeLog("factoryMap2集合："+factoryMap2);
        factoryMap1.put("MATNR",factoryMap2.get("MATNR"));
//        bb.writeLog("sureNullPoint03------");
//        factoryMap1.put("ZFLAG",factoryMap2.get("ZFLAG"));
//        bb.writeLog("sureNullPoint04------");
//        factoryMap1.put("LOEVM",factoryMap2.get("LOEVM"));
//        bb.writeLog("sureNullPoint05------");
        factoryMap1.put("BESKZ",factoryMap2.get("BESKZ"));
//        bb.writeLog("sureNullPoint06------");
//        至此factoryMap1集合中存储了所有factory节点所需要的键值对

        bb.writeLog("再次输出factoryMap1，确认是否含有MATNR，ZFLAG元素"+factoryMap1);

        String[] saleParams = {"MATNR","VKORG","VTWEG","DWERK","SKTOF","VERSG","KONDM","KTGRM","MTPOS","PRODH","ZFLAGXSZZC","LOEVMXSZZC"};
        String saleSql = "SELECT MATNR,VKORG,VTWEG,DWERK,SKTOF,VERSG,KONDM,KTGRM,MTPOS,PRODH,ZFLAGXSZZC,LOEVMXSZZC from formtable_main_117 a join formtable_main_117_dt5 b on a.id=b.mainid";
        Map<String, Object> saleMap = Data(saleParams, saleSql+where);
        bb.writeLog("saleMap集合："+saleMap);
        bb.writeLog("进入XML组装------");

//        XML组装
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Element root = document.createElement("ROOT");
        document.appendChild(root);
//        group节点
        bb.writeLog("创建group节点");
        Element group = document.createElement("GROUP");
        bb.writeLog("创建子节点并赋值");
        for (String groupParam : groupParams) {
            if ("BISMT".equals(groupParam) || "SICHT_P".equals(groupParam) || "SICHT_Q".equals(groupParam)){
                appendChild(document,group,groupParam, "");
                bb.writeLog("个别节点控制添加成功");
            }else if ("ZFLAGJTC".equals(groupParam) || "LOEVMJTC".equals(groupParam)){
                appendChild(document,group,groupParam.substring(0,5),Util.null2String(groupMap.get(groupParam).toString()));
            }else{
                appendChild(document,group,groupParam,Util.null2String(groupMap.get(groupParam).toString()));
                bb.writeLog(groupParam+"节点添加成功");
            }
        }
        root.appendChild(group);
//        factory节点
        Element factoryEle = document.createElement("FACTORY");
        for (String factoryParam : factoryParams) {
            if ("PERKZ".equals(factoryParam)){
                appendChild(document,factoryEle,"PERKZ","");
            }else if ("ZFLAGGCC".equals(factoryParam) || "LOEVMGCC".equals(factoryParam)){
                appendChild(document,factoryEle,factoryParam.substring(0,5),factoryMap1.get(factoryParam).toString());
            }
            else {
                appendChild(document,factoryEle,factoryParam,factoryMap1.get(factoryParam).toString());
            }
            bb.writeLog(factoryParam+"节点添加成功");
        }
        root.appendChild(factoryEle);
        bb.writeLog("factory节点添加成功");
//        sale节点
        Element sale = document.createElement("SALE");
        for (String saleParam : saleParams) {
            if ("ZFLAGXSZZC".equals(saleParam) || "LOEVMXSZZC".equals(saleParam)){
                appendChild(document,sale,saleParam.substring(0,5),saleMap.get(saleParam).toString());
                bb.writeLog(saleParam+"节点添加成功,它的值是："+saleMap.get(saleParam).toString());
            }else {
                appendChild(document,sale,saleParam,saleMap.get(saleParam).toString());
                bb.writeLog(saleParam+"节点添加成功");
            }

        }
        root.appendChild(sale);
        bb.writeLog("sale节点添加成功");

        bb.writeLog("result: " + createXmlToString(document));

        return createXmlToString(document);
    }



    /**
     * 查询节点所需要的数据
     * */
    private Map<String,Object> Data(String[] params, String sql){
        Map<String,Object> resultData = new HashMap<>();
        RecordSet rs = new RecordSet();
        rs.executeQuery(sql);
        while (rs.next()){
            for (String param : params) {
                resultData.put(param, Util.null2String(rs.getString(param)));
            }
        }
        return resultData;
    }



    /**
     * document对象中添加子项
     * @param document ducument对象
     * @param parent 父元素
     * @param key 元素标签
     * @param value 元素content值
     */
    private static void appendChild(Document document, Element parent, String key, String value) {
        Element child = document.createElement(key);
        if(child != null) {
            child.setTextContent(value);
        }
        parent.appendChild(child);
    }

    /**
     * 生成xml字符串
     * @param document Document树对象
     * @return 整个xml字符串
     */
    private static String createXmlToString(Document document){
        String xmlString = null;
        try {
            // 创建TransformerFactory工厂对象
            TransformerFactory transFactory = TransformerFactory.newInstance();
            // 通过工厂对象, 创建Transformer对象
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");
            //使Xml自动换行, 并自动缩进
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");  //中间的参数网址固定写法(这里还没搞懂)
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                          //是否设置缩进（indent: yes|no）
            // 创建DOMSource对象并将Document加载到其中
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 使用Transformer的transform()方法将DOM树转换成XML
            transformer.transform(domSource, new StreamResult(bos));
            xmlString = bos.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return xmlString;
    }
}
